from pycocotools.coco import COCO
import numpy as np
import skimage.io as io
import json

#import matplotlib
#matplotlib.use('tkagg')#emmm，感觉前面coco把它改成agg了
#import matplotlib.pyplot as plt

import matplotlib
matplotlib.use("Qt5Agg")  # 声明使用QT5
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

import pylab
#pylab.rcParams['figure.figsize'] = (8.0, 10.0)

class MyFigure(FigureCanvas):
    def __init__(self,width=5, height=4, dpi=100):
        #第一步：创建一个创建Figure
        self.fig = Figure(figsize=(width, height), dpi=dpi)
        #第二步：在父类中激活Figure窗口
        super(MyFigure,self).__init__(self.fig) #此句必不可少，否则不能显示图形
        #第三步：创建一个子图，用于绘制图形用，111表示子图编号，如matlab的subplot(1,1,1)
    #第四步：就是画图，【可以在此类中画，也可以在其它类中画】
    def plotimg(self):
        biaozhu()
        self.axes1 = self.fig.add_subplot(111)
        self.axes1.axis('off')
        I = io.imread('biaozhu.png')
        self.axes1.imshow(I)

def biaozhu():
    #val_info = ".\\annotations\coco_wholebody_val_v1.0.json"
    val_info = ".\\modified\\1_229553.json"
    val_image = r'D:\dasishang\coco\dip2020\mycoco\images\val2017'

    coco = COCO(val_info)  # 导入coco

    cats = coco.loadCats(coco.getCatIds()) #导入coco的所有分类（只有person）
    nms=[cat['name'] for cat in cats]
    print('COCO categories: \n{}\n'.format(' '.join(nms)))

    nms = set([cat['supercategory'] for cat in cats])
    print('COCO supercategories: \n{}'.format(' '.join(nms)))

    all_ids = coco.imgs.keys()#5000张不同的图
    print(len(all_ids))

    #对于该函数, 如果不指定参数, 则返回所有类的 id, 否则, 返回指定类的 id ( 类可以通过 ‘name’, ‘supercategory’ 或 ‘id’ 指定).
    #def getCatIds(self, catNms=[], supNms=[], catIds=[]):
    #person的序号：1
    person_id = coco.getCatIds(catNms=['person'])
    print(person_id)


    #def loadCats(self, ids=[]):
    #函数返回的是从 json 文件加载进来的 80 类对象. 这个函数接收一个 id list 作为参数, 如果没有指定 id 参数, 那么函数返回也为一个空 list. 

    #得到含人标签的图片列表：一共2693
    person_imgs_id = coco.getImgIds(catIds=person_id)
    print(len(person_imgs_id))

    #加载其中具体的一张图片,以image对象为载体
    #img = coco.loadImgs(person_imgs_id[np.random.randint(0,len(person_imgs_id))])[0]
    img = coco.loadImgs(person_imgs_id[0])[0]
    # loadImgs() 返回的是只有一个元素的列表, 使用[0]来访问这个元素
    # 列表中的这个元素又是字典类型, 关键字有: ["license", "file_name", 
    #  "coco_url", "height", "width", "date_captured", "id"]
    #self.axes1.imshow(I)
    #self.axes1.axis('off')
    I = io.imread(img['coco_url'])
    #print(I.shape)
    plt.imshow(I)
    plt.axis('off')
    annIds = coco.getAnnIds(imgIds=img['id'], catIds=person_id, iscrowd=None)
    #print(annIds)
    annIds=[annIds[0]]
    anns = coco.loadAnns(annIds)
    #print(anns)
    #anns[0]['keypoints'].append([1,1,10,1,10,10,1,10])
    #anns[0]['keypoints']=[0,0,0,10,10,2,20,20,2,10,20,2,0,0,0,100,100,2,100,200,1, 210, 356, 2, 420, 274, 2, 153, 193, 2, 343, 261, 2, 0, 0, 0, 437, 403, 2, 197, 413, 2, 264, 303, 1, 0, 0, 0, 345, 475, 1]
    #anns[0]['keypoints']=[0,0,0,100,100,1,200,200,1,0,0,0,0,0,0,0,0,0,400,400,1,0,0,0,400,450,1,150,150,2]
    while(len(anns[0]['keypoints'])<51):
        anns[0]['keypoints'].append(0)
    coco.showAnns(anns)
    #print(len(anns[0]['keypoints']))
    #print(len(anns[1]['keypoints']))
    plt.savefig("biaozhu.png")
    plt.show()
    #return I

if __name__ == "__main__":
    biaozhu()
    '''
    #path1 = ".\\modified\\1_369037.json"
    path1 = ".\\annotations\\coco_wholebody_val_v1.0.json"
    with open(path1,'rb') as f:
        data = json.load(f)
        #print(data)
        print(type(data["images"][0]["id"]))
        # 字典类型
        #print(type(data))
    '''